cmake_minimum_required(VERSION 3.10)
project(imgui VERSION 1.0 LANGUAGES CXX)

if(POLICY CMP0072)
  cmake_policy(SET CMP0072 NEW)
endif()

find_package(glfw3 REQUIRED)
find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)

# 设置头文件目录
set(IMGUI_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include)

include_directories(
        ${IMGUI_INCLUDE_DIR}
        ${IMGUI_INCLUDE_DIR}/imgui
        ${IMGUI_INCLUDE_DIR}/backends
)

# 自动收集 include/imgui 目录下的所有头文件
file(GLOB IMGUI_PUBLIC_HEADERS
    "${IMGUI_INCLUDE_DIR}/imgui/*.h"
    "${IMGUI_INCLUDE_DIR}/imgui/*.hpp"
    "${IMGUI_INCLUDE_DIR}/backends/*.h"
    "${IMGUI_INCLUDE_DIR}/backends/*.hpp"
)

# 源文件
file(GLOB IMGUI_SRC
    "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/src/basckends/imgui_impl_glfw.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/src/basckends/imgui_impl_opengl3.cpp"
)

add_library(imgui SHARED ${IMGUI_SRC})
target_include_directories(imgui
    PUBLIC
    $<BUILD_INTERFACE:${IMGUI_INCLUDE_DIR}/imgui>
    $<INSTALL_INTERFACE:include/imgui>
)
target_link_libraries(imgui glfw GLEW::GLEW OpenGL::GL)

set_target_properties(imgui PROPERTIES PUBLIC_HEADER "${IMGUI_PUBLIC_HEADERS}")

# 安装规则
install(TARGETS imgui
    EXPORT imguiTargets
    LIBRARY DESTINATION lib
    ARCHIVE DESTINATION lib
    PUBLIC_HEADER DESTINATION include/imgui
)

# 安装 CMake 配置文件
include(CMakePackageConfigHelpers)
configure_package_config_file(
    cmake/imguiConfig.cmake.in
    ${CMAKE_CURRENT_BINARY_DIR}/imguiConfig.cmake
    INSTALL_DESTINATION lib/cmake/imgui
)

install(FILES
    ${CMAKE_CURRENT_BINARY_DIR}/imguiConfig.cmake
    DESTINATION lib/cmake/imgui
)

install(EXPORT imguiTargets
    FILE imguiTargets.cmake
    NAMESPACE imgui::
    DESTINATION lib/cmake/imgui
)

# 导出包信息
export(EXPORT imguiTargets
    FILE ${CMAKE_CURRENT_BINARY_DIR}/imguiTargets.cmake
    NAMESPACE imgui::
)

# uninstall target
if(NOT TARGET uninstall)
    configure_file(
        "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in"
        "${CMAKE_CURRENT_BINARY_DIR}/cmake/cmake_uninstall.cmake"
        IMMEDIATE @ONLY)
    add_custom_target(uninstall
        COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake/cmake_uninstall.cmake
        COMMENT "Uninstalling..."
    )
endif()